package com.haifeng.asms.api.controller.third;

import cn.hutool.core.util.ObjectUtil;
import com.haifeng.asms.commons.common.Rest;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.enums.AuthResponseStatus;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.request.AuthAlipayRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 *  支付宝登录测试
 * </p>
 *
 * @author: Haifeng
 * @date: 2020-06-26
 */
@RestController
@RequestMapping("/oauth")
public class AlipayLoginController {

    @GetMapping("/render")
    public void renderAuth(HttpServletResponse response) throws IOException {
        AuthRequest authRequest = getAuthRequest();
        response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));
    }

    @GetMapping("/callback")
    public Object login(AuthCallback callback) {
        AuthRequest authRequest = getAuthRequest();
        AuthResponse authResponse = authRequest.login(callback);
        if (ObjectUtil.isNotNull(authResponse.getCode()) && authResponse.getCode() == AuthResponseStatus.SUCCESS.getCode()){

            //TODO 此处引导用户去注册绑定手机号等信息...

            return Rest.success(authResponse.getData());
        }
        return Rest.error(authResponse.getCode(),authResponse.getMsg());
    }

    private AuthRequest getAuthRequest() {
        return new AuthAlipayRequest(AuthConfig.builder()
                .clientId("2021001169637539")
                // 填写自己的
                .clientSecret("")
                .alipayPublicKey("")
                .redirectUri("http://172.17.28.49:8080/oauth/callback")
                .build());
    }
}
